package com.monitor.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.jfinal.log.Logger;
import com.monitor.model.Log;
import com.monitor.model.Sensor;
import com.monitor.model.Warning;
import com.monitor.utils.APPConfig;
import com.monitor.utils.DateUtil;
import com.monitor.utils.PropertyUtil;

/**
 * 监控线程
 * @author HanChen
 *
 */
public class MonitorDataThread implements Runnable {
	private static Logger log = Logger.getLogger(MonitorServerSocket.class);
	private Warning warn;

	public MonitorDataThread(Warning warn) {
		this.warn = warn;
	}

	@Override
	public void run() {
		log.info("》》》》监控线程开始运行《《《《");
		Map<Sensor, Date> normalMap = warn.getNormal();
		Map<Sensor, Date> warnMap = warn.getWarn();
		Map<String, Integer> temp = warn.getTemperature();
		List<Sensor> sensors = Sensor.sensor.findAll();
		List<Sensor> notUseSensors  = new ArrayList<Sensor>();
		PropertyUtil prop = new PropertyUtil(APPConfig.FILENAME, "UTF-8");
		boolean notUse = false;
		boolean wraning = false;
		for (Sensor sensor : sensors) {
			// 如果map里不包含数据库里查出的sensor就说明有节点没有工作
			if (!normalMap.containsKey(sensor)) {
				// 报警 有节点没工作
				notUseSensors.add(sensor);
				notUse = true;
				wraning = true;
			}
		}
		
		if(notUse){
			log.debug("报警 有节点没工作");
			Alarm.sendMessage(3292, "#datatime#="+DateUtil.getDateNow());
			log.info("保存日志信息 有节点未工作");
			for (Sensor sensor : notUseSensors) {
				Log.me.saveMsg("节点" + sensor.getInt("id") + "(" + sensor.getStr("name")
						+ ")  未工作");
			}
			
		}

		// 检查warnMap是否为空 不为空就需要报警
		if (!warnMap.isEmpty()) {
			log.debug("报警 危险值");
			log.debug("map:"+warnMap.size());
			
			for (Sensor sensor : warnMap.keySet()) {
				log.info("保存日志信息 危险数据");
				Log.me.saveMsg("节点" + sensor.getInt("id") + "(" + sensor.getStr("name")
						+ ") 采集到危险数据,其中温度是"+temp.get("temp"));
				Alarm.sendMessage(3293, "#temp=#"+String.valueOf(temp.get("temp")));
			}
			wraning = true;
		}
		
		if(!wraning){
			prop.set("firstTimes", "0");
			prop.set("secondAlarm", "false");
			prop.set("secondLastTime", "0");
			prop.store();
		}
		// 最后清空两个map
		normalMap.clear();
		warnMap.clear();
		if(temp != null){
			temp.clear();
		}
		log.info("》》》》监控线程结束《《《《");
	}

}
